package com.bobo.dao.category;

import com.bobo.dao.BaseDao;
import com.bobo.model.Category;
import com.bobo.model.Photo;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by bobo on 2016/10/16.
 */
public class CategoryDaoImpl extends BaseDao<Category> implements ICategoryDao {
    @Override
    public Integer create(Category category) {
        String sql = "INSERT INTO t_category(`name`,photo_id) VALUES(?,?)";
        return create(sql, category.getName(), category.getPhoto().getId());
    }

    @Override
    public boolean update(Category category) {
        String sql = "UPDATE t_category c SET c.`name`=?,c.status=?,c.photo_id=? WHERE c.id=?";
        return update(sql, category.getName(), category.getStatus(), category.getPhoto().getId(), category.getId());
    }

    @Override
    public Category getById(Integer id) {
        String sql = "SELECT c.id cid,c.`name` came,c.`status` cs,p.id pid,p.img  " +
                " FROM t_category c,t_photo p  " +
                " WHERE c.photo_id=p.id " +
                " AND c.`id`=?";
        Category category = new Category();
        Photo photo = new Photo();
        ResultSet rs = getObject(sql, id);
        try {
            while (rs.next()) {
                category.setId(id);
                category.setName(rs.getString("came"));
                category.setStatus(rs.getInt("cs"));

                photo.setId(rs.getInt("pid"));
                photo.setImg(rs.getString("img"));
                category.setPhoto(photo);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return category;
    }

    @Override
    public List<Category> getCategories(Integer current, Integer pageSize, Integer status) {
        StringBuffer sql = new StringBuffer("SELECT c.id cid,c.`name` came,c.`status` cs, " +
                " p.id pid,p.img FROM t_category c,t_photo p where c.photo_id=p.id");
        List<Category> categories = new ArrayList<>();
        ResultSet rs;
        if(status!=null){
            sql.append(" and c.status=?");
            rs = pager(sql.toString(), current, pageSize, status);
        }else {
           rs = pager(sql.toString(), current, pageSize);
        }
        try {
            while (rs.next()) {
                Category category = new Category();
                category.setId(rs.getInt("cid"));
                category.setName(rs.getString("came"));
                category.setStatus(rs.getInt("cs"));

                Photo photo = new Photo();
                photo.setId(rs.getInt("pid"));
                photo.setImg(rs.getString("img"));
                category.setPhoto(photo);
                categories.add(category);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return categories;
    }

}
